package org.zebra.message;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import org.dromara.email.jakarta.comm.config.MailSmtpConfig;
import org.dromara.email.jakarta.core.factory.MailFactory;
import org.dromara.oa.api.OaSender;
import org.dromara.oa.core.provider.factory.OaFactory;
import org.dromara.sms4j.api.dao.SmsDao;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

/**
 * @author zhanghongbin
 */
@AutoConfiguration
@EnableConfigurationProperties(MailProperties.class)
public class MessageConfig implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        MailProperties mailProperties = SpringUtil.getBean(MailProperties.class);
        if (StrUtil.isBlank(mailProperties.getSmtp())
                || mailProperties.getPort() == 0
                || StrUtil.isBlank(mailProperties.getUserName())
                || StrUtil.isBlank(mailProperties.getPassword())
                || StrUtil.isBlank(mailProperties.getFromAddress())) {
            return;
        }
        MailSmtpConfig config = MailSmtpConfig.builder()
                .smtpServer(mailProperties.getSmtp())
                .fromAddress(mailProperties.getFromAddress())
                .port(String.valueOf(mailProperties.getPort()))
                .isAuth(String.valueOf(mailProperties.isAuth()))
                .isSSL(String.valueOf(mailProperties.isSsl()))
                .maxRetries(ObjUtil.defaultIfNull(mailProperties.getMaxRetries(), 0))
                .retryInterval(ObjUtil.defaultIfNull(mailProperties.getRetryInterval(), 0))
                .username(mailProperties.getUserName())
                .password(mailProperties.getPassword())
                .build();
        MailFactory.put(mailProperties.getFromAddress(), config);
    }

    @Bean
    @ConditionalOnProperty(prefix = "zebra.message", name = "oa")
    public OaSender oaSender() {
        return OaFactory.getSmsOaBlend("oa-config");
    }

    @Bean
    public SmsDao smsDao() {
        return new SmsDaoPlus();
    }

    @Bean
    @ConditionalOnMissingBean(value = SmsExceptionAdvice.class)
    public SmsExceptionAdvice smsExceptionAdvice() {
        return new SmsExceptionAdvice();
    }
}
